/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { FileSet, hvigor } from '@ohos/hvigor';
import { ProjectConfig } from '@ohos/hvigor-arkts-compose';
import fse from 'fs-extra';
import path from 'path';
import { InjectUtil } from '../../utils/inject-util.js';

import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { ArkCompile } from '../ark-compile.js';
import { TaskNames } from '../common/task-names.js';

import { BuildUnitTestHook } from './build-unit-test-hook.js';
import { UnitTestProcessProfile } from './unit-test-process-profile.js';
import { CommonConst } from '../../const/common-const.js';

/**
 * 单元测试ArkTS编译 stage模型
 *
 * @since 2023/4/23
 */
export class UnitTestArkCompile extends ArkCompile {
  logger: OhosLogger = OhosLogger.getLogger(UnitTestArkCompile.name);

  declareInputFiles(): FileSet {
    return super.declareInputFiles();
  }

  protected async doTaskAction(): Promise<void> {
    await super.doTaskAction();
  }

  protected async initDefaultArkCompileConfig(): Promise<ProjectConfig> {
    this.flushBuildConfig();
    const projectConfig: ProjectConfig = {
      ...(await super.initDefaultArkCompileConfig()),
      aceModuleBuild: path.resolve(this.pathInfo.getInterMediatesAssetsPath(), this.codeType),
    };
    const modules = InjectUtil.getEntryModulesName();
    if (modules.length) {
      projectConfig.mainModulePath = hvigor.getNodeByName(modules[0])?.getNodePath();
    }
    if (projectConfig.obfuscationOptions) {
      delete projectConfig.obfuscationOptions;
    }
    if (projectConfig.testFrameworkPar) {
      projectConfig.testFrameworkPar.testMode = CommonConst.UNIT_TEST;
    }
    return projectConfig;
  }

  initTaskDepends(): void {
    this.declareDependsList(BuildUnitTestHook.name, UnitTestProcessProfile.name);
  }

  /**
   *落盘buildConfig文件，传递abc生成路径给测试矿机
   */
  flushBuildConfig() {
    if (this.moduleModel.isHspModule() && hvigor.isCommandEntryTask(TaskNames.Task.TEST.name)) {
      const buildConfigPath = this.pathInfo.getTestBuildConfigPath();
      fse.ensureDirSync(path.dirname(buildConfigPath));
      fse.writeJSONSync(buildConfigPath, {
        aceModuleBuild: path.resolve(this.pathInfo.getInterMediatesAssetsPath(), this.codeType),
      });
    }
  }
}
